using System;
using System.Xml;
using System.Collections;
using System.IO;

namespace bOS.XML.Data
{
	public abstract class XMLObjectSet : CollectionBase
	{
		public XMLObjectSet()
		{
		}

		public XMLObject this[ int index ]  
		{
			get  
			{
				return( (XMLObject) List[index] );
			}
			set  
			{
				List[index] = value;
			}
		}

		public int Add (XMLObject obj)
		{
			return this.List.Add (obj);
		}

		public int Add (XMLObjectSet obj)
		{
			return this.List.Add (obj);
		}

		public void RemoveAll()
		{
			this.List.Clear ();
		}

		abstract public void Init();

		virtual public void Parse (string sXml) 
		{
			try
			{
				System.Xml.XmlDocument document = new System.Xml.XmlDocument();
				document.LoadXml (sXml);
				System.Xml.XmlNode root = document.FirstChild;

				this.Parse (root);
			}
			catch ( XmlException xmlErr)
			{
				throw new bOS.Exception.bOSException("Impossible to parse XML." + xmlErr.Message);
			}
			catch ( System.Exception err)
			{
				throw new bOS.Exception.bOSException(err.Message);
			}
		}

		abstract public void Parse(System.Xml.XmlNode node);

		abstract public bOS.XML.XMLNode GetXMLNode();

		virtual public string GetXML()
		{
			return this.GetXMLNode().GetXML(false, 0);
		}

		public string GetXML(bool bIndent, int iLevel)
		{
			return this.GetXMLNode().GetXML(bIndent, iLevel);
		}

		public void Load(string sFileName)
		{
			try
			{
				XmlDocument xmlDocument = new XmlDocument();
				xmlDocument.Load(sFileName);

				System.Xml.XmlNode root = xmlDocument.FirstChild;

				this.Parse (root);
			}
			catch ( XmlException)
			{
				throw new bOS.Exception.bOSException("Impossible to parse XML");
			}
			catch ( System.IO.FileNotFoundException )
			{
				throw new bOS.Exception.bOSException("Impossible to find XML file");
			}
			catch ( System.Exception )
			{
				throw new bOS.Exception.bOSException("Unknow Err.");
			}
		}

		public void Save(string sFileName)
		{
			try
			{
				StreamWriter sw = File.CreateText(sFileName);
				sw.Write(this.GetXML (true, 0));
				sw.Flush ();
				sw.Close();
			}
			catch ( System.IO.IOException ) 
			{
				throw new bOS.Exception.bOSException("Impossible to save XML file");
			}
			catch ( System.Exception )
			{
				throw new bOS.Exception.bOSException("Unknow Err.");
			}
		}
	}
}
